package org.jeecg.modules.cascv.image.service.merge.ranshaogui;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.ByteUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
@Service
@Slf4j
public class Ranshaogui2Service extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "TGMTYY1601_09EH_31_HMRCSAPP5,TGMTYY1601_09EH_31_HMRCSAPP6,TGMTYY1601_09EH_31_HMRCSAPP7,6D23H_70H,6D24H_70H,6D25H_70H";
    }

    // Integer width = 1280;
    // Integer height = 1024;
    // 2345的 width = 1296;

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {

        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
        startEndFlag = startEndFlag.split(";")[0];
         dataFrames = (dataFrames.split(";")[1]).substring(2).trim();
       // dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        StringBuilder queue = LaptopConstant.imageData.get(key);
        composite(idsName, key, conJson, dataFrames, queue, startEndFlag, secondStr, subSecondStr);

        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String startEndFlag, String secondStr, String subSecondStr) {
        int width = 1280; //1296
        int height = 1024;
        if ("TGMTYY1601_09EH_31_HMRCSAPP5".equalsIgnoreCase(idsName)||"6D23H_70H".equalsIgnoreCase(idsName)) {
            width = 1296;
        }
        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag) || !LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            if (null == queue) {
                queue = new StringBuilder();
                queue.append(dataFrames);
            } else {
                queue.append(dataFrames);
            }
            LaptopConstant.imageData.put(key, queue);
        } else if (LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            queue.append(dataFrames);

            while (queue.length() < width * height * 2) {
                queue.append("0");
            }
            while (queue.length() > width * height * 2) {
                queue.delete(queue.length() - 1, queue.length());
            }
            String imgHexStr = queue.toString();
            String idStr = IdWorker.getIdStr();




            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                byte[] byteBuffer = ByteUtil.getBytes(imgHexStr);
            try {


                FileImageOutputStream io = null;
            File savefile = new File("/data/images/"+idStr+".jpeg");
            try {
                io = new FileImageOutputStream(savefile);
                io.write(byteBuffer, 0, byteBuffer.length);

            } catch (Exception e) {
                throw e;
            } finally {
                try {
                    if (io != null) {
                        io.close();
                    }
                } catch (Exception e) {
                    throw e;
                }

            }

        //  转换png
            BufferedImage input = ImageIO.read(savefile);
            File outPutfile = new File("/data/images/"+idStr+".jpeg".replace("." + "jpeg",".png"));
            ImageIO.write(input,"jpeg",outPutfile);
            outPutfile = new File("/data/images/"+idStr+".jpeg".replace("." + "jpeg",".png"));
            ImageIO.write(input,"png",outPutfile);
        } catch (Exception e) {
            log.info("燃烧柜图片生成失败," +e);
            e.printStackTrace();

        }

                    String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" +idStr+".png";
              //log.info(imageUrl);
                   content.put("imageUrl", imageUrl);
                    content.put("idsName", idsName);

                    String[] split = secondStr.split(":");
                    content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                   content.put("key", key);
                log.info("燃烧柜6D23H_70H,6D24H_70H,6D25H_70H, 合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");
                return content;
                },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

            LaptopConstant.imageData.remove(key);//清空图片数据

        }
        return true;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("E:\\11图像数据\\cut2\\燃烧\\T19700429033131_0001_009E_F1_00_6DCD_2024_0070_70_6D24_000000000.txt");
        Ranshaogui2Service ranshaogui2Service = new Ranshaogui2Service();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            ranshaogui2Service.merge(jsonObject, "6D24H_70H", "6D24H_70H");
        }

    }

    public static int do16to8(int a) {
        double aa = a * 1.0;
        double bb = aa / 65535.0;
        aa = bb * 255.0;
        a = new Double(aa).intValue();
        return a;
    }
}
